#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n + 1);
        auto g = f;
        g[0] = 0x3f3f3f3f;

        int sum = 0;
        for (auto k : nums) sum += k;

        int fmax = INT_MIN, gmin = INT_MAX;

        for (int i = 1; i <= n; i++)
        {
            f[i] = max(nums[i - 1], f[i - 1] + nums[i - 1]);
            g[i] = min(nums[i - 1], g[i - 1] + nums[i - 1]);
            fmax = max(fmax, f[i]);
            gmin = min(gmin, g[i]);
        }

        return sum == gmin ? fmax : max(fmax, sum - gmin);
    }
};